<?php

/**
 * Action类
 *
 * @package    lib
 * @subpackage core
 * @author     苏宁 <snsnsky@gmail.com>
 *
 * $Id$
 */

namespace lib\core;

use lib\util\Securimage;
use \Common\Bridge;

class AdminAction
{

    /**
     * 应用程序类
     *
     * @var Application
     * @access protected
     */
    protected $app;

    /**
     * 分页技术，每页大小，方便后台调试,
     */
    const PAGE_SIZE = 20;

    /**
     * 构造函数
     *
     * @param Application &$app 应用程序类
     */
    public function __construct(& $app)
    {
        $this->app = $app;

        //权限认证
        $auth = $_SESSION['admin_auth_list'];
        if (!defined('NO_CHECK')) {
            if (empty($_SESSION['admin_info'])) {
                HDshowMsg('请先登录', ['type' => 'error', 'url' => ADMIN_DOMAIN_ROOT . 'index.php']);
            }
            if (!isset($auth[SITE_AUTH])) {
                HDshowMsg('您无权访问此页面', ['type' => 'error']);
            }
        }
    }

    public function doDefault()
    {

    }

    /**
     * 统一输出
     *
     * @param mixed   $data  输出数据
     * @param string  $type  输出类型
     * @param boolean $exit  是否结束程序, true结束, false不结束
     * @param mixed   $extra 附加数据
     * @return mixed
     */
    public function output($data, $type = 'json', $exit = true, $extra = '')
    {
        switch ($type) {
            case 'debug':
                echo '<pre>';
                print_r($data);
                echo '</pre>';
                break;
            case 'xml':
                // echo $this->_toXml();
                break;
            case 'json':
            default:
                if (isset($_GET['callback'])) {
                    $jsonp = $_GET['callback'];
                    echo $jsonp . '(' . json_encode($data, JSON_UNESCAPED_UNICODE) . ')';
                } else {
                    echo json_encode($data, JSON_UNESCAPED_UNICODE);
                }
        }

        if ($exit) {
            exit();
        }

        return true;
    }

    /**
     * 输出验证输出处理
     */
    public function doCode()
    {
        $options = [
            'image_width' => 96,
            'image_height' => 27,
            'text_scale' => 0.6, //字体比例
        ];
        $img = new Securimage($options);
        $img->show();
    }

    /**
     * 后台操作日志
     *
     * @param string $itemname 对象名称
     * @param int    $itemid   对象ID
     * @param string $logflag  细分操作标识 如: edit/add/update
     * @param string $desc     详细日志，可以记录一下数据变更什么的
     */
    public function adminLog($itemname, $itemid, $logflag, $desc)
    {
        $db = Bridge::pdo(Bridge::DB_ADMIN_W);

        if (defined('SITE_AUTH')) {
            $menu = \Admin\Menu::getMenuByKey(SITE_AUTH);
        } else {
            define('SITE_AUTH', 'admin-login');
            $menu['Name'] = '管理员登录';
        }

        $user = $_SESSION['admin_info'];

        $log['UserId'] = $user['AdminUserId'];
        $log['UserName'] = $user['AdminUserName'];
        $log['MenuKey'] = SITE_AUTH;
        $log['MenuName'] = $menu['Name'];
        $log['ItemName'] = $itemname;
        $log['ItemId'] = $itemid;
        $log['LogFlag'] = $logflag;
        $log['Log'] = is_string($desc) ? $desc : json_encode($desc, JSON_UNESCAPED_UNICODE);
        $log['CreateTime'] = date("Y-m-d H:i:s");

        $db->insert('AdminLog', $log);

        return;
    }

    /**
     * 分页函数，返回html
     *
     * @param int $count 总数量
     * @param int $per   每页数量
     * @param int $now   当前页数
     * @return string
     */
    public function pagination($count, $per, $now)
    {
        $page_key = 'page'; //分页传值的key
        $baseurl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        empty($now) && $now = 1;//如果传0，则为第一页
        unset($_GET[$page_key]);
        if (!empty($_GET)) {
            $baseurl .= '?';
            foreach ($_GET as $k => $v) {
                $baseurl .= $k . '=' . $v . '&';
            }
        } else {
            $baseurl .= '?';
        }

        $pages = intval(ceil($count / $per));
        $min = 1;
        $max = $pages >= 10 ? 10 : $pages;
        if ($pages > 10 && $now > 5) {
            $min = $now - 5;
            $max = $now + 5;
        }
        $max > $pages && $max = $pages;
        $html = '<nav><ul class="pagination pagination-sm"><li><a href="' . $baseurl . 'page=1" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
        for ($n = $min; $n <= $max; $n++) {
            $url = $baseurl . 'page=' . $n;
            if ($n == $now) {
                $html .= '<li class="active"><a href="' . $url . '">' . $n . '</a></li>';
            } else {
                $html .= '<li><a href="' . $url . '">' . $n . '</a></li>';
            }

        }

        $url = $baseurl . 'page=' . $pages;
        if ($max < $pages) {
            $html .= '<li><a><input type="text" style="height: 17px; width: 40px;font-size:10px;padding:0 3px;" class="form-control" onkeydown=" if(event.keyCode==13) { var pagesize = this.value; var url = \'' . $baseurl . 'page=\'+pagesize+\')\'; location.href= url}"> </li></a><li><a href="' . $url . '">' . $pages . '</a></li>';
        }
        $html .= '<li> <a href="' . $url . '" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li></ul></nav>';
        if ($pages == 1) {
            return '';
        }

        return $html;
    }
}
